package com.code.bz.managers;

import com.alibaba.fastjson.JSON;
import com.code.bz.models.checktoken.BzResponse;
import com.code.bz.models.checktoken.TokenSwapManageResponse;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * http调用的相关管理类
 *
 * @author xiaoyaowang
 */
@Component
@Slf4j
public class HttpManager {

    @Value("${tokenSwap.manageUrlCheckToken}")
    private String tokenSwapManageCheckTokenUrl;

    @Value("${task.token}")
    private String taskToken;

    @Value("${telegram.url}")
    private String telegramUrl;

    @Value("${accessToken}")
    private String accessToken;

    @Value("${bz.url}")
    private String bzUrl;

    @Autowired
    private RestTemplate restTemplate;

    private static final String ACCEPT = "Accept";

    /**
     * 验证token
     *
     * @param token 登录token
     * @return 验证与否
     */
    public Boolean verifyToken(String token) {
        //设置请求参数
        Map<String, Object> postData = Maps.newHashMapWithExpectedSize(1 << 4);
        postData.put("token", token);
        String requestBody = JSON.toJSONString(postData);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<TokenSwapManageResponse> response = restTemplate.exchange(tokenSwapManageCheckTokenUrl, method, formEntity, TokenSwapManageResponse.class);
        log.info("验证token结果:{}", JSON.toJSONString(response));
        TokenSwapManageResponse body = response.getBody();
        if (null != body) {
            String rtnCode = body.getCode();
            if ("0".equals(rtnCode)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 添加BZ体验计划
     *
     * @param bzAccount bz账号
     * @return 验证与否
     */
    public int addBzExperience(String bzAccount) {
        //设置请求参数
        Map<String, Object> postData = Maps.newHashMapWithExpectedSize(1 << 4);
        postData.put("userAccount", bzAccount);
        String requestBody = JSON.toJSONString(postData);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<BzResponse> response = restTemplate.exchange(bzUrl + "financialOrder/experience-bz-plan", method, formEntity, BzResponse.class);
        log.info("验证token结果:{}", JSON.toJSONString(response));
        BzResponse body = response.getBody();
        if (null != body) {
            int rtnCode = body.getCode();
            if (rtnCode == 1) {
                return (int) body.getData();
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }


    /**
     * 发送重新发送截图任务的消息
     *
     * @param chatId 群组唯一标识
     * @param text   发送的内容
     */
    @Async
    public void sendReSendPhoto(Long chatId, String text) {
        log.info("发送的内容：{}", text);
        String uri = telegramUrl + "/bot" + taskToken + "/sendMessage?chat_id=" + chatId + "&text=" + text + "&parse_mode=HTML";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        log.info("发送的消息的响应:{}", strBody);
    }

    /**
     * 构造http请求的头部信息
     *
     * @return http头部信息
     */
    private HttpHeaders getJsonHeader() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add(ACCEPT, MediaType.APPLICATION_JSON.toString());
        headers.add("accessToken", accessToken);
        return headers;
    }

}
